import { fileURLToPath, URL } from 'node:url'
import { defineConfig, loadEnv, UserConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { AntDesignVueResolver } from 'unplugin-vue-components/resolvers'
import Icons from 'unplugin-icons/vite'
import IconsResolver from 'unplugin-icons/resolver'
import svgLoader from 'vite-svg-loader'
import eslintPlugin from 'vite-plugin-eslint'
import { createHtmlPlugin } from 'vite-plugin-html'
import viteCompression from 'vite-plugin-compression'
// import { visualizer } from 'rollup-plugin-visualizer'

export default defineConfig(({ mode }) => {
  const { VITE_BASE_PATH, VITE_TITLE } = loadEnv(mode, process.cwd())

  const config: UserConfig = {
    base: VITE_BASE_PATH,
    plugins: [
      vue(),
      eslintPlugin(), //eslint检查
      Components({
        dirs: ['src/components'], //自动引入该目录下组件
        extensions: ['vue'],
        resolvers: [
          //自动引入antdv组件
          AntDesignVueResolver({
            importStyle: false, // css in js
            resolveIcons: true, //自动引入antdv图标组件
          }),
          //自动引入Iconify的图标组件,使用: <IconifyStreamlineEmojisAirplane/> Iconify前缀，StreamlineEmojisAirplane图标组件名。https://icones.js.org/
          IconsResolver({ prefix: 'iconify' }),
        ],
        dts: './types/components.d.ts',
      }),
      //按需打包Iconify中的图标
      Icons({
        scale: 1, // 缩放比 相对1em
        autoInstall: true, // 自动安装
        compiler: 'vue3', // 编译方式
      }),
      //自动引入对应库的api
      AutoImport({
        imports: ['vue', 'vue-router', 'pinia'],
        dts: './types/auto-imports.d.ts',
        eslintrc: {
          enabled: true,
        },
      }),
      svgLoader(), //svg可以像组件一样引入使用并设置颜色大小
      createHtmlPlugin({
        inject: {
          data: {
            //index.html变量注入
            title: VITE_TITLE,
          },
        },
      }),

      viteCompression({
        // gzip 压缩
        threshold: 10240, // 文件超过10k压缩
        algorithm: 'gzip',
        ext: '.gz',
        deleteOriginFile: false, // 压缩后是否删除源文件
      }),
      // visualizer(), //打包后在根目录下生成stats.html,分析文件体积
    ],
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: '@import "src/styles/common.scss";', // 添加全局变量
        },
      },
    },
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url)),
      },
    },
    build: {
      rollupOptions: {
        output: {
          chunkFileNames: 'assets/js/[name]-[hash].js',
          entryFileNames: 'assets/js/[name]-[hash].js',
          assetFileNames: 'assets/[ext]/[name]-[hash].[ext]',
          //拆包并行加载
          manualChunks: {
            vue: ['vue'],
            antdv: ['ant-design-vue'],
            axios: ['axios'],
            echarts: ['echarts'],
          },
        },
      },
      // 消除打包大小超过500kb警告
      // chunkSizeWarningLimit: 2000,
      minify: 'terser',
      /** 在打包代码时移除 console.log、debugger 和 注释 */
      terserOptions: {
        compress: {
          drop_console: true,
          drop_debugger: true,
          pure_funcs: ['console.log'],
        },
        format: {
          comments: false, //是否保留注释
        },
      },
    },
    server: {
      //本地服务
      port: 3001, //端口号
      open: true, //启动时是否自动打开
      proxy: {
        '/api': {
          target: 'http://localhost:3002',
          changeOrigin: true,
          rewrite: path => path.replace('/api/', '/'),
        },
      },
    },
  }
  return config
})
